package com.yindi.sftp;

import com.yindi.sftp.config.Parameters;
import com.yindi.sftp.utils.SmartSshUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@Slf4j
public class SftpClient {

    public static void main(String[] args) throws InterruptedException {
        //处理配置文件
        Parameters.init();
        log.info("公共配置文件：{}", Parameters.common);
        log.info("下载配置文件：{}", Parameters.upload);
        log.info("上传配置文件：{}", Parameters.download);
        int i = 1;
        while (true) {
            log.info("正在轮询： 第{}轮", i);
            long startTime = System.currentTimeMillis();
            //处理上传的
            ArrayList<CompletableFuture<?>> completableFutures = new ArrayList<>();
            Parameters.Upload upload = Parameters.upload;
            List<Parameters.Dir> uploadDirs = upload.getDirs();
            for (Parameters.Dir dir : uploadDirs) {
                if("1".equals(dir.getActive())){
                    CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> SmartSshUtils.upLoadFileBySsh(dir, upload.getTmpDir()));
                    completableFutures.add(voidCompletableFuture);
                }
            }

            //处理下载的
            Parameters.Download download = Parameters.download;
            List<Parameters.Dir> downloadDirs = download.getDirs();
            for (Parameters.Dir dir : downloadDirs) {
                if("1".equals(dir.getActive())) {
                    CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> SmartSshUtils.downLoadFileBySsh(dir, download.getTmpDir()));
                    completableFutures.add(voidCompletableFuture);
                }
            }

            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(completableFutures.stream().toArray(CompletableFuture[]::new));
            try {
                voidCompletableFuture.get(Long.parseLong(Parameters.common.getSleepTime()) * 1000 * 60, TimeUnit.SECONDS);
                long endTime = System.currentTimeMillis();
                log.info("第{}轮 轮询完成 耗时：{}秒", i++, (endTime - startTime) / 1000);
            } catch (ExecutionException | InterruptedException | TimeoutException e) {
                e.printStackTrace();
                log.error("本次任务已经超时：重新处理");
            } finally {
                Thread.sleep(Long.parseLong(Parameters.common.getSleepTime()) * 1000 * 60);
            }
        }
    }
}
